//
//  ByteConvert.m
//  DB3
//
//  Created by keisun on 2018/12/4.
//  Copyright © 2018年 keisun. All rights reserved.
//

//构建联合体
typedef union
{
    float f;
    unsigned long ldata;
}FloatType;

#import "ByteConvert.h"

@implementation ByteConvert

//字节数组转成float
+(float)byteToFloat_WithByte:(unsigned char[])byte{
        FloatType fty;
        fty.ldata = 0;
        fty.ldata = byte[3];
        fty.ldata = (fty.ldata<<8) | byte[2];
        fty.ldata = (fty.ldata<<8) | byte[1];
        fty.ldata = (fty.ldata<<8) | byte[0];
        float f = fty.f;
        return f;
}

//float转字节数组
+(void)floatToByte:(unsigned char[])byte withFloat:(float)f{
    //把float类型的指针强制转换为unsigned char型
    unsigned char *pdata = (unsigned char *)&f;
    for (int i=0; i<4; i++) {
        byte[i] = *pdata;
        pdata++;
    }
}

//字节数组转成int
+(int)byteToInt_WithByte:(unsigned char[])byte{
    int temp=0;
    int iValue=0;
    for(int i=0;i<4;i++){
        iValue<<=8;
        temp=byte[i]&0xff;  //这里用来获取byte[i]的低8位
        iValue|=temp;
    }
    return iValue;
}

//int转字节数组
+(void)intToByte:(unsigned char[])byte withInt:(int)i{
    for(int m=0;m<4;m++)
    {
        byte[m]=(i>>(24-m*8));
    }
}

+(int)dataToInt:(NSData *)data{
    Byte *byte = (Byte *)[data bytes];
    return [self byteToInt_WithByte:byte];
}

+(float)dataToFloat:(NSData *)data{
    Byte *byte = (Byte *)[data bytes];
    return [self byteToFloat_WithByte:byte];
}

+(NSString *)dataToString:(NSData *)data{
    Byte *byte = (Byte *)[data bytes];
    NSString *string = [[NSString alloc] initWithBytes:byte length:[data length] encoding:NSUTF8StringEncoding];
    return string;
}

@end

